#include "MprpcChannel.h"
#include "MprpcApplication.h"
#include "rpcheader.pb.h"
#include "MprpcController.h"
#include "ZooKeeperUtil.h"
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void MprpcChannel::CallMethod(const google::protobuf::MethodDescriptor *method,
                              google::protobuf::RpcController *controller, const google::protobuf::Message *request,
                              google::protobuf::Message *response, google::protobuf::Closure *done)
{
    const google::protobuf::ServiceDescriptor *sd = method->service();
    std::string service_name = sd->name();
    std::string method_name = method->name();

    int args_size = 0;
    std::string args_str;
    if (request->SerializeToString(&args_str))
    {
        args_size = args_str.size();
    }
    else
    {
        controller->SetFailed("serialize request error!");
        return;
    }
    mprpc::RpcHeader rpc_header;
    rpc_header.set_service_name(service_name);
    rpc_header.set_method_name(method_name);
    rpc_header.set_args_size(args_size);

    uint32_t header_size = 0;
    std::string rpc_header_str;
    if (rpc_header.SerializeToString(&rpc_header_str))
    {
        header_size = rpc_header_str.size();
    }
    else
    {
        controller->SetFailed("serialize epc header error!");
        return;
    }
    std::string send_rpc_str;
    send_rpc_str.append((char *)&header_size, 4);
    send_rpc_str += rpc_header_str;
    send_rpc_str += args_str;

    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == clientfd)
    {
        char errText[512] = {0};
        sprintf(errText, "create socket error! error: %d", errno);
        controller->SetFailed(errText);
        close(clientfd);
        return;
    }

    // 读取配置文件rpcserver的信息
    // std::string ip = MprpcApplication::GetInstance().GetConfig().Load("rpcserverip");
    // uint16_t port = atoi(MprpcApplication::GetInstance().GetConfig().Load("rpcserverport").c_str());
    // rpc调用方想调用service_name的method_name服务，需要查询zk上该服务所在的host信息
    ZkClient zkCli;
    zkCli.Start();
    //  /UserServiceRpc/Login
    std::string method_path = "/" + service_name + "/" + method_name;
    // 127.0.0.1:8000
    std::string host_data = zkCli.GetData(method_path.c_str());
    if (host_data == "")
    {
        controller->SetFailed(method_path + " is not exist!");
        return;
    }
    int idx = host_data.find(":");
    if (idx == -1)
    {
        controller->SetFailed(method_path + " address is invalid!");
        return;
    }

    std::string ip = host_data.substr(0, idx);
    uint16_t port = atoi(host_data.substr(idx+1, host_data.size()-idx).c_str()); 

    // std::string ip = MprpcApplication::GetConfig().Load("rpcserverip");
    // uint16_t port = atoi(MprpcApplication::GetConfig().Load("rpcserverport").c_str());

    sockaddr_in server_addr;
    std::memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(ip.c_str());

    if (-1 == connect(clientfd, (sockaddr *)&server_addr, sizeof(server_addr)))
    {
        char errText[512] = {0};
        sprintf(errText, "connect socket error! error: %d", errno);
        controller->SetFailed(errText);
        close(clientfd);
        return;
    }

    if (-1 == send(clientfd, send_rpc_str.c_str(), send_rpc_str.size(), 0))
    {
        char errText[512] = {0};
        sprintf(errText, "send error! error: %d", errno);
        controller->SetFailed(errText);
        close(clientfd);
        return;
    }
    char recv_buf[1024] = {0};
    int recv_size = 0;
    if (-1 == (recv_size = recv(clientfd, recv_buf, 1024, 0)))
    {
        char errText[512] = {0};
        sprintf(errText, "recv error! error: %d", errno);
        controller->SetFailed(errText);
        close(clientfd);
        return;
    }
    if (recv_size == 0)
    {
        controller->SetFailed("rpcService close!");
        close(clientfd);
        return;
    }
    std::string response_str(recv_buf, recv_size);
    if (!response->ParseFromString(response_str))
    {
        char errText[512] = {0};
        sprintf(errText, "parse error! response_str: %s", response_str.c_str());
        controller->SetFailed(errText);
        close(clientfd);
        return;
    }
    close(clientfd);
}